package com.sky.aspect;

import com.sky.annotation.PreAuthorize;
import com.sky.context.BaseContext;
import com.sky.entity.Employee;
import com.sky.exception.BaseException;
import com.sky.mapper.EmployeeMapper;
import com.sky.mapper.PermissionMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class PreAuthorizeAspect {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Before("execution(* com.sky.controller.admin..*(..))&&@annotation(com.sky.annotation.PreAuthorize)")
    public void limitAccessCalculate(JoinPoint jp) {

        // 得到目标方法签名
        MethodSignature ms = (MethodSignature) jp.getSignature();
        // 权限注解
        PreAuthorize preAuthorize = ms.getMethod().getAnnotation(PreAuthorize.class);
        String methodPre = preAuthorize.value();

        // 根据当前用户id得到该用户权限标识符集合
        List<String> permissions = permissionMapper.selectByEmployeeId(BaseContext.getCurrentId());
        // 当前用户
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());

        if (employee.getUsername().equals("admin")) return;
        // 权限集合
        boolean contains = permissions.contains(methodPre);
        if (!contains) {
            throw new BaseException("您无权限!");
        }
    }
}
